package com.macrounion.atv.task;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.macrounion.atv.cache.DeviceCache;
import com.macrounion.atv.cache.ProtocolCache;
import com.macrounion.atv.dto.req.SnmpGetRouterReqDto;
import com.macrounion.atv.processor.RegProcessor;
import com.macrounion.atv.service.entity.CurrentData;
import com.macrounion.atv.service.entity.ProtocolC;
import com.macrounion.atv.service.entity.ext.DeviceExt;
import com.macrounion.atv.utils.CommandUtil;
import com.macrounion.device.enums.SnmpVersionEnum;
import com.macrounion.device.snmp.Snmp1;
import com.macrounion.device.snmp.config.SnmpTargetConfig;

/**
 * snmp协议数据刷新
 * @author Administrator
 *
 */
@Component
public class SnmpGetTask {
	
	@Autowired
	private DeviceCache deviceCache;
	@Autowired
	private ProtocolCache protocolCache;
	@Autowired
	private Snmp1<SnmpGetRouterReqDto> snmp;
	@Autowired
	private RegProcessor regProcessor;
	
	//@Scheduled(cron="${timely.snmpGet}")
	public void getData() {
		if(!regProcessor.canUse())
			return;
		List<DeviceExt> devices = deviceCache.getDevicesByStype("snmp");
		if(CollectionUtils.isEmpty(devices))
			return;
		if(!CollectionUtils.isEmpty(devices)) {
			devices.forEach(device->{
				List<ProtocolC> ps = protocolCache.getByProtocolId(device.getProtocolId());
				if(!CollectionUtils.isEmpty(ps))
					new Thread(()->{getSnmpData(device,ps);}).start();
			});
		}
	}
	
	private void getSnmpData(DeviceExt device, List<ProtocolC> ps) {
		SnmpGetRouterReqDto dto = new SnmpGetRouterReqDto();
		dto.setDevice(device);
		dto.setProtocolcs(ps);
		SnmpTargetConfig<SnmpGetRouterReqDto> config = new SnmpTargetConfig<SnmpGetRouterReqDto>(device.getDeviceCode(),SnmpVersionEnum.praseEnum(device.getSnmpv()));
		config.setGetOids(ps.parallelStream().filter(p->{return p.getTrap().equals(0);}).map(ProtocolC :: getMid).collect(Collectors.toList()));
		config.setData(dto);
		try {
			snmp.sendGet(config);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
